import { FC, ReactElement, useEffect, useState, useCallback } from 'react'
import * as qiniu from 'qiniu-js'
import { ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons'
import { Button, Upload, message, Modal, Table, Progress } from 'antd'
import type { ColumnsType } from 'antd/es/table'
import { connect, Dispatch, Loading, SchoolUserStateType } from 'umi'
import { Location } from 'history-with-query'
import { getStorage } from '@/utils'
import FilePreview from './components/file-preview'
import styles from './index.less'
const { confirm } = Modal
interface IProps {
  schoolUserModel: SchoolUserStateType
  dispatch: Dispatch
  location: Location
}

const TopicPage: FC<IProps> = ({
  dispatch,
  schoolUserModel,
  location
}): ReactElement => {
  const { batchCode, type } = location.query as {
    batchCode: string
    type: string
  }
  let { topicList, qiniuToken, uploadFileList } = schoolUserModel
  const [fileType, setFileType] = useState<string>('')
  const [filePath, setFilePath] = useState<string>('')
  const [previewShow, setPreviewShow] = useState<boolean>(false)
  const [process, setProcess] = useState<number>(0)
  const [showProcess, setShowProcess] = useState<boolean>(false)
  const [currentProcess, setCurrentProcess] = useState<string>('')
  const [dataSource, setDataSource] = useState<any[]>([])

  interface DataType {
    index: string | null
    fileName: string
    fileSize: string
    updateTime: string
    operation: string | null
  }

  const filePreview = (filePath: string) => {
    setFilePath(filePath)
    const fileType = filePath.substring(filePath.lastIndexOf('.') + 1)
    // office文件和压缩文件新开窗口或下载
    if (
      [
        'ppt',
        'pptx',
        'xlsx',
        'docx',
        'xls',
        'doc',
        'rar',
        'zip',
        '7z'
      ].includes(fileType)
    ) {
      window.open(filePath)
      return
    }
    setFileType(fileType)
    setPreviewShow(true)
  }

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: '150px',
      align: 'center',
      render: (text: string, record: any, index: number) => (
        <span>{(index + 1).toString().padStart(2, '0')}</span>
      )
    },
    {
      title: '材料名称',
      dataIndex: 'fileName',
      key: 'fileName',
      width: '300px',
      align: 'center',
      render: (text: string, record: any) => (
        <span
          className={styles['file-name']}
          onClick={() => filePreview(record.url)}
        >
          {text}
        </span>
      )
    },
    {
      title: '文件大小',
      dataIndex: 'fileSize',
      key: 'fileSize',
      width: '300px',
      align: 'center'
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      align: 'center',
      width: '300px'
    },
    {
      title: '操作',
      key: 'operation',
      dataIndex: 'operation',
      align: 'center',
      width: '100px',
      render: (_: string, record: any) => (
        <>
          <span className={styles['del-btn']}>删除</span>
        </>
      )
    }
  ]

  // 查询评价批次题目信息
  const getBatchQuestionInfo = useCallback(
    (batchCode: string, type: string) => {
      dispatch({
        type: 'schoolUserModel/function_getBatchQuestionInfo',
        payload: {
          batchCode,
          type
        }
      })
    },
    []
  )

  // 获取七牛token
  const getQiniuToken = useCallback(() => {
    dispatch({
      type: 'schoolUserModel/function_getQiniuToken'
    })
  }, [])

  // 查询用户题目上传信息
  const getUserAnswer = useCallback((batchCode: string, userCode: string) => {
    dispatch({
      type: 'schoolUserModel/function_getUserAnswer',
      payload: {
        batchCode,
        userCode
      }
    })
  }, [])

  // 七牛上传
  const handleUpload = (
    options: any,
    code: string,
    type: string,
    onlyKey: string
  ) => {
    setShowProcess(true)
    setCurrentProcess(onlyKey)
    const { file, onSuccess, onProgress } = options
    if (
      !['.pdf', '.mp4', '.mp3', '.png', '.jpg', '.jpeg', '.gif'].includes(
        file.name?.substring(file.name.lastIndexOf('.'))
      )
    ) {
      message.error('允许上传类型: .pdf、.mp4、.mp3、.png、.jpg、.jpeg、.gif')
      setShowProcess(false)
      return
    }
    let observe = {
      next(res: any) {
        setProcess(res.total.percent.toFixed(2))
        onProgress({ percent: res.total.percent })
      },
      error(err: any) {},
      complete(res: any) {
        //完成后的操作
        //上传成功以后会返回key 和 hash  key就是文件名了！

        saveUserAnswer(
          batchCode,
          code,
          type,
          'http://cdn8.lepeisheng.com/' + res.key,
          file.size
        )
        onSuccess()
      }
    }
    let key =
      'xdpj' +
      '/' +
      batchCode +
      '/' +
      getStorage('userCode') +
      '/' +
      code +
      '/' +
      type +
      '/' +
      file.name

    let region = qiniu.region.z2
    const putExtra = {
      fname: '', // fname: string，文件原文件名
      params: {}, // params: object，用来放置自定义变量
      mimeType: undefined // mimeType: undefined || array，用来限制上传文件类型，为 undefined 时表示不对文件类型限制；限制类型放到数组里： ["image/png", "image/jpeg", "image/gif"]
    }
    const config = {
      useCdnDomain: true,
      region, //z0华东区域 z1华北区域  z2代表华南区域  na0北美区域   as0新加坡区域
      domain: 'http://cdn8.lepeisheng.com'
    }
    let observable = qiniu.upload(file, key, qiniuToken, putExtra, config)
    let subscription = observable.subscribe(observe)
  }

  // 保存题目用户上传信息
  const saveUserAnswer = (
    batchCode: string,
    code: string,
    type: string,
    url: string,
    fileSize: number
  ) => {
    dispatch({
      type: 'schoolUserModel/function_saveUserAnswer',
      payload: {
        batchCode,
        code,
        type,
        url,
        userCode: getStorage('userCode'),
        fileSize
      },
      callback: (response) => {
        if (response.code === 200) {
          message.success('上传成功')
          setShowProcess(false)
          getUserAnswer(batchCode, getStorage('userCode')!)
        }
      }
    })
  }

  // 删除用户上传的资料信息
  const handleDel = (code: string, type: string, fileName: string) => {
    confirm({
      title: '删除?',
      icon: <ExclamationCircleOutlined />,
      content: '确定删除该信息资料',
      okText: '确定',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: 'schoolUserModel/function_deleteUserAnswer',
          payload: {
            batchCode,
            code,
            type,
            userCode: getStorage('userCode')!,
            fileName
          },
          callback: (response) => {
            if (response.code === 200) {
              message.success('删除成功')
              getUserAnswer(batchCode, getStorage('userCode')!)
            }
          }
        })
      },
      onCancel() {
        console.log('Cancel')
      }
    })
  }

  useEffect(() => {
    getBatchQuestionInfo(batchCode, type)
    getQiniuToken()
    getUserAnswer(batchCode, getStorage('userCode')!)
  }, [])

  useEffect(() => {
    if (topicList.length) {
      topicList = topicList.map((item) => ({
        ...item,
        type: (item.type as string).split(',').map((item) => ({
          typeName: item
        }))
      }))
      topicList.forEach((item) => {
        uploadFileList.forEach((v) => {
          if (v.questionCode === item.code) {
            ;(item.type as any[]).forEach((k) => {
              if (v.type === k.typeName) {
                if (!k.children) {
                  k.children = []
                }
                k.children.push(v)
              }
            })
          }
        })
      })
      setDataSource(topicList)
    }
  }, [topicList, uploadFileList])

  return (
    <>
      <div className={styles['outter-wrapper']}>
        <div className={styles['inner-wrapper']}>
          <div className={styles['module-title']}>
            <span>资料上传</span>
            <span className={styles['allow-type']}>
              允许上传类型: .pdf、.mp4、.mp3、.png、.jpg、.jpeg、.gif
            </span>
          </div>
          <div className={styles['module-content']}>
            {dataSource?.map((item) => (
              <div key={item.code} className={styles['topic-item']}>
                <div className={styles['title-wrapper']}>
                  {item.title}
                  {item.title ? '、' : null}
                  {item.name}
                </div>
                <div className={styles['type-item']}>
                  {(item.type as any[]).map((v) => (
                    <div key={v.typeName}>
                      <div className={styles['table-header']}>
                        <span className={styles['type-name']}>
                          {v.typeName}
                        </span>
                        <Upload
                          showUploadList={false}
                          customRequest={(options) =>
                            handleUpload(
                              options,
                              item.code,
                              v.typeName,
                              `${item.code}${v.typeName}`
                            )
                          }
                          accept=".pdf,.mp4,.mp3,.png,.jpg,.jpeg,.gif"
                        >
                          <Button
                            type="primary"
                            icon={<PlusOutlined />}
                            className={styles['upload-btn']}
                          >
                            上传
                          </Button>
                        </Upload>
                        {showProcess &&
                          currentProcess === `${item.code}${v.typeName}` && (
                            <Progress percent={process} />
                          )}
                      </div>

                      <div className={styles['table-wrapper']}>
                        <Table
                          rowKey="updateTime"
                          columns={columns}
                          dataSource={v.children}
                          pagination={false}
                          locale={{ emptyText: '暂无数据' }}
                          onRow={(record) => {
                            return {
                              onClick: (event) => {
                                if (
                                  (event.target as HTMLElement).innerText ==
                                  '删除'
                                ) {
                                  handleDel(
                                    item.code,
                                    v.typeName,
                                    record.fileName
                                  )
                                }
                              } // 点击行
                            }
                          }}
                        />
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>

          <FilePreview
            visible={previewShow}
            filePath={filePath}
            fileType={fileType}
            hide={() => setPreviewShow(false)}
          />
        </div>

        <p className={styles['copy-right']}>
          Copyright@ 2016 成都乐培生科技有限公司 蜀ICP备15018125号
        </p>
      </div>
    </>
  )
}

const mapStateToProps = ({
  schoolUserModel,
  loading
}: {
  schoolUserModel: SchoolUserStateType
  loading: Loading
}) => {
  return {
    schoolUserModel,
    evaluationLoding: loading.models.evaluationModel
  }
}

export default connect(mapStateToProps)(TopicPage)
